package com.wondersgroup.fjzlpt.org.service.impl.jgqy.qysq;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.quick.framework.exception.ServiceException;
import com.quick.framework.util.LoggerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.wondersgroup.fjzlpt.org.dao.inter.jgqy.qysq.QysqDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.jgqy.qysq.QysqKsxxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.jgqy.qysq.QysqYljgDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.yljgxx.YljgxxDAO;
import com.wondersgroup.fjzlpt.org.service.inter.jgqy.qysq.QysqService;


@Service
public class QysqServiceImpl implements QysqService{

	@Autowired
	private QysqDAO qysqDAO;
	
	@Autowired
	private QysqYljgDAO qysqYljgDAO;
	
	@Autowired
	private YljgxxDAO yljgxxDao;
	
	@Autowired
	private QysqKsxxDAO qysqKsxxDAO;
	
	/**
	 * 保存
	 * @param map
	 * @return
	 */
	public JSONObject save(Map<String, String> map) {
		ResultObject ro = new ResultObject();
		String method = map.get("method");
		if("add".equals(method)){
			insert(map, ro);
		}
		else if("update".equals(method)){
			update(map, ro);
		}
		/*else if("qysq".equals(method)){
			qysq(map, ro);
		}*/
		return (JSONObject)JSON.toJSON(ro);
	}
	
	/**
	 * 新增
	 * @param map
	 * @param ro
	 */
	private void insert(Map map, ResultObject ro){
		if(qysqDAO.isExit(map)){
			ro.changeFaultState("该医联体已存在，请修改医联体名称！");
		}else{
			try {
				String YLTID = UUID.randomUUID().toString().toUpperCase();
				map.put("YLTID", YLTID);
				map.put("YLTZT", "0");
				map.put("SFXY", "0");
				map.put("CJSJ", new Date());
				qysqDAO.insert(map);
				/**创建关联表插入的多条记录*/
				String yljgids = map.get("YLJGIDS").toString();
				String ZDYLJGID = map.get("ZDYLJGID").toString();
				String[] ids = yljgids.split(",");
				List<Map> list = new ArrayList<Map>();
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				for (String str : ids) {
					//,QYSJ,DQSJ
					Map  ma = new HashMap();
					ma.put("GLID", UUID.randomUUID().toString().toUpperCase());
					ma.put("YLTID", YLTID);
					ma.put("YLJGID", str);
					ma.put("JLZT", "1");
					ma.put("QYYXQ", map.get("QYYXQ"));
					ma.put("QYSJ", sdf.parse(map.get("QYSJ").toString()));
					ma.put("DQSJ", sdf.parse(map.get("DQSJ").toString()));
					if((ZDYLJGID).equals(str)){
						ma.put("JGLX", "3");
					}else{
						ma.put("JGLX", "1");
					}
					ma.put("QYSQSJ", new Date());
					if(ZDYLJGID.equals(str)){
						ma.put("QYZT", "03");
					}else{
						ma.put("QYZT", map.get("QYZT"));
					}
					list.add(ma);
				}
				qysqYljgDAO.insertBatch(list);
				/**判断是否为专科联盟*/
				if("03".equals(map.get("YLTLX"))){
					List<Map> ksList = new ArrayList<Map>();
					for (Map<String, String> ma : list) {
						String yljgid = ma.get("YLJGID");
						/**获取传入的多个ksdm*/
						String ksdms = map.get("KSDMS").toString();
						ma.remove("QYZT");
						ids = ksdms.split("/");
						for (String str : ids) {
							if(str.indexOf(yljgid) != -1){
								String[] strAry = str.split(":");
								if("null".equals(strAry[1])){
									ma.put("KSDM", "null");
									ksList.add(ma);
								}else{
									String[] ksAry = strAry[1].split(",");
									for (int i = 0; i < ksAry.length; i++) {
										Map<String, String> mm = new HashMap<String, String>();
										mm.putAll(ma);
										mm.put("KSDM", ksAry[i]);
										ksList.add(mm);
									}
								}
							}
						}
					}
					/**插入专科联盟科室信息*/
					qysqKsxxDAO.insertBatch(ksList);
				}
				
			}catch (Exception e) {
				LoggerUtil.error(e.getMessage());
				throw new ServiceException("ERR-000541","新增签约申请失败！");
			}
		} 
	}
	
	/**
	 * 更新
	 * @param map
	 * @param ro
	 */
	private void update(Map<String, String> map, ResultObject ro){
		try {
			qysqDAO.updateForPrimaryKey(map);
			/**根据医联体id删除记录*/
			qysqYljgDAO.delete(map);
			/**创建关联表插入的多条记录*/
			String yljgids = map.get("YLJGIDS");
			String ZDYLJGID = map.get("ZDYLJGID");
			String YLTID = map.get("YLTID");
			String[] ids = yljgids.split(",");
			List<Map> list = new ArrayList<Map>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (String str : ids) {
				Map  ma = new HashMap();
				ma.put("GLID", UUID.randomUUID().toString().toUpperCase());
				ma.put("YLTID", YLTID);
				ma.put("YLJGID", str);
				ma.put("QYYXQ", map.get("QYYXQ"));
				ma.put("QYSJ", sdf.parse(map.get("QYSJ")));
				ma.put("DQSJ", sdf.parse(map.get("DQSJ")));
				if((ZDYLJGID).equals(str)){
					ma.put("JGLX", "3");
				}else{
					ma.put("JGLX", "1");
				}
				ma.put("QYSQSJ", new Date());
				if(ZDYLJGID.equals(str)){
					ma.put("QYZT", "03");
				}else{
					ma.put("QYZT", map.get("QYZT"));
				}
				list.add(ma);
			}
			qysqYljgDAO.insertBatch(list);
			/**判断是否为专科联盟*/
			if("03".equals(map.get("YLTLX"))){
				/**根据医联体id删除科室记录*/
				qysqKsxxDAO.delete(map);
				List<Map> ksList = new ArrayList<Map>();
				for (Map<String, String> ma : list) {
					String yljgid = ma.get("YLJGID");
					/**获取传入的多个ksdm*/
					String ksdms = map.get("KSDMS");
					ma.remove("QYZT");
					ids = ksdms.split("/");
					for (String str : ids) {
						if(str.indexOf(yljgid) != -1){
							String[] strAry = str.split(":");
							if("null".equals(strAry[1])){
								ma.put("KSDM", "null");
								ksList.add(ma);
							}else{
								System.out.println(ma.toString());
								String[] ksAry = strAry[1].split(",");
								for (int i = 0; i < ksAry.length; i++) {
									Map<String, String> mm = new HashMap<String, String>();
									mm.putAll(ma);
									mm.put("KSDM", ksAry[i]);
									ksList.add(mm);
								}
							}
						}
					}
				}
				/**插入专科联盟科室信息*/
				qysqKsxxDAO.insertBatch(ksList);
			}
			
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000542","更新签约申请失败！");
		}
	}

	
	/**
	 * 签约申请
	 * @param map
	 * @param ro
	 */
	/*private void qysq(Map<String, String> map, ResultObject ro){
		try {
			String yltid = map.get("YLTID");
			String yljgid = map.get("YLJGID");
			String ksdms = map.get("KSDMS");
			if("03".equals(map.get("YLTLX")) && !StringUtils.isEmpty(ksdms)){
				String[] ary = ksdms.split(",");
				List<Map> ksList = new ArrayList<Map>();
				for (String str : ary) {
					Map ma = new HashMap<>();
					ma.put("YLTID", yltid);
					ma.put("YLJGID", yljgid);
					ma.put("KSDM", str);
				}
				*//**插入专科联盟科室信息*//*
				qysqKsxxDAO.insertBatch(ksList);
			}
			map.put("GLID", UUID.randomUUID().toString().toUpperCase());
			map.put("JGLX", "2");
			map.put("QYSQSJ", (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
			map.put("QYZT", "02");
			qysqYljgDAO.insert(map);
		} catch (Exception e) {
			ro.changeFaultState("签约申请失败！");
			throw new RuntimeException("签约申请失败！", e);
		}
	}*/
	
	
	/**
	 * 分页查询
	 * @param map
	 * @return
	 */
	//@Cacheable("queryPage")
	public JSONObject queryPage(Map<String, String> map) {
		return qysqDAO.queryPage(map);
	}

	/**
	 * 根据条件查询所有
	 * @param map
	 * @return
	 */
	public JSONArray queryList(Map<String, String> map) {
		JSONArray jsary = new JSONArray();
		try {
			jsary = qysqDAO.queryAll(map);
			//签约状态代码转中文
			JSONObject qyztObj = JSONObject.parseObject("{'01':'暂存','02':'待接收','03':'已签约','04':'拒绝','05':'已到期'}");
			for(int i=0;i<jsary.size();i++){
				JSONObject item = jsary.getJSONObject(i);
				item.put("QYZT", qyztObj.get(item.get("QYZT")));
			}
			
			JSONObject json = new JSONObject();
			json.put("YLTMC", "签约名称");
			json.put("ZDYLJGMC", "主导机构");
			json.put("YLJGMC", "签约机构");
			json.put("YLTLXMC", "医联体类型");
			json.put("QYSJ", "申请时间");
			json.put("QYYXQMC", "签约有效期");
			json.put("QYZT", "状态");
			jsary.add(0,json);
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000543","根据id查询医联体失败！");
		}
		return jsary;
	}

	/**
	 * 查询医疗机构和科室信息
	 * @param map
	 * @return
	 */
	public JSONArray queryYljgAndKs(Map<String, String> map) {
		JSONArray ja = yljgxxDao.queryList(map);
		/**机构排序*/
		String[] strs = (map.get("YLJGIDS")).split(",");
		JSONArray tempJa = new JSONArray();
		JSONObject tempJo = new JSONObject();
		for (String string : strs) {
			Iterator jaIt =  ja.iterator();
			while(jaIt.hasNext()){
				tempJo = JSONObject.parseObject(jaIt.next().toString());
				if((string).equals(tempJo.getString("PTJGID"))){
					tempJa.add(tempJo);
				}
			}
		}
		ja = tempJa;
		JSONObject json1 = new JSONObject();
		JSONObject json2 = new JSONObject();
		List<String> list = new ArrayList<String>(); 
		if(!ja.isEmpty()){
			/**获取平台机构ID*/
			Iterator<Object> it = ja.iterator();
			while (it.hasNext()) {
				json1 = JSONObject.parseObject(it.next().toString());
				list.add(json1.getString("PTJGID"));
			}
			it = ja.iterator();
			/**根据机构ID查询科室信息*/
			ja = yljgxxDao.queryKsxx(list);
			JSONArray jarr = new JSONArray();
			while (it.hasNext()) {
				json1 = JSONObject.parseObject(it.next().toString());
				JSONArray jsonary = new JSONArray();
				/**遍历获取机构科室列表*/
				Iterator<Object> ksIt = ja.iterator();
				while (ksIt.hasNext()) {
					json2 = JSONObject.parseObject(ksIt.next().toString());
					if((json1.getString("PTJGID")).equals(json2.getString("PTJGID"))){
						String ksdm = json2.getString("KSDM");
						if(!StringUtils.isEmpty(ksdm)){
							json2.put("KSDMPK", json2.getString("KSDM")+":"+json2.getString("PTJGID"));
							json2.putAll(json1);
							jsonary.add(json2);
						}
					}
				}
				json1.put("KSMC", json1.getString("YLJGMC"));
				json1.put("KSDMPK", json1.getString("PTJGID"));
				json1.put("KSDM", json1.getString("PTJGID"));
				json1.put("children", jsonary);
				jarr.add(json1);
			}
			ja = jarr;
		}
		return ja;
	}

	/**
	 * 查询签约机构信息
	 * @param map
	 * @return
	 */
	public JSONArray queryQyJg(Map<String, String> map) {
		JSONArray ja = new JSONArray();
		if("03".equals(map.get("YLTLX"))){
			ja = qysqDAO.queryQyJg(map);
			JSONArray ary = qysqKsxxDAO.query(map);
			Iterator<Object> it = ja.iterator();
			ja = new JSONArray();
			while (it.hasNext()) {
				JSONArray temp = new JSONArray();
				String ksmc = "";
				String ksdm = "";
				JSONObject json1 = JSONObject.parseObject(it.next().toString());
				Iterator<Object> ksIt = ary.iterator();
				while (ksIt.hasNext()) {
					JSONObject json2 = JSONObject.parseObject(ksIt.next().toString());
					if((json1.getString("PTJGID")).equals(json2.getString("YLJGID")) 
							&& (json1.getString("GLID")).equals(json2.getString("GLID"))){
						ksmc += json2.getString("KSMC")+",";
						ksdm += json2.getString("KSDM")+",";
						temp.add(json2);
					}
				}
				if(StringUtils.isEmpty(ksmc)){
					json1.put("KSMC", "");
					json1.put("KSDM", "");
				}else{
					json1.put("KSMC", ksmc.substring(0, ksmc.lastIndexOf(",")));
					json1.put("KSDM", ksdm.substring(0, ksdm.lastIndexOf(",")));
				}
				json1.put("KSXX", temp);
				ja.add(json1);
			}
		}else{
			ja = qysqDAO.queryQyJg(map);
		}
		return ja;
	}

	/**
	 * 获取科室信息 
	 * @param map
	 * @return
	 */
	public JSONObject querZdjgKsxx(Map<String, String> map) {
		JSONObject res = new JSONObject();
		/**获取关联ID*/
		JSONObject jo = qysqYljgDAO.queryZdjg(map);
		map.put("GLID", jo.getString("GLID"));
		JSONArray ja = qysqKsxxDAO.query(map);
		JSONObject temp = new JSONObject();
		String ksmc = "";
		String ksdm = "";
		for (int i = 0; i < ja.size(); i++) {
			temp = (JSONObject) ja.get(i);
			ksmc += temp.getString("KSMC")+",";
			ksdm += temp.getString("KSDM")+",";
		}
		res.put("KSMC", ksmc.substring(0,ksmc.lastIndexOf(",")));
		res.put("KSDM", ksdm.substring(0,ksdm.lastIndexOf(",")));
		return res;
	}


}
